package com.ljl.ningwei.service.impl;

import com.ljl.ningwei.service.FileService;
import com.ljl.ningwei.common.utils.AliOssUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 文件服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class FileServiceImpl implements FileService {

    private final AliOssUtil aliOssUtil;


    // 正则表达式匹配关键部分
    private final Pattern pattern = Pattern.compile(
            "https?://[^/]+/image/(\\d{4})/(\\d{2})/([a-f0-9]+)_(\\d+)×(\\d+)\\.(\\w+)"
    );
    // 图片类型
    private static final Map<String, String> ALLOWED_IMAGE_TYPES = Map.of(
            "image/jpeg", "jpg",
            "image/png", "png",
            "image/gif", "gif"
    );


    // 文档类型
    private static final Map<String, String> ALLOWED_DOCUMENT_TYPES = Map.of(
            "application/pdf", "pdf",
            "application/msword", "doc",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx"
    );

    @Override
    public String upload(MultipartFile file) throws IOException {
        String fullPath = getFileName(file);
        fullPath = aliOssUtil.upload(file.getBytes(), fullPath);
        return fullPath;
    }

    @Override
    public Double getImageAr(String path) {
        Matcher matcher = pattern.matcher(path);
        if (matcher.find()) {
            Integer width = Integer.parseInt(matcher.group(4));  // 812
            Integer height = Integer.parseInt(matcher.group(5)); // 375
            if (ObjectUtils.isNotEmpty(width) && ObjectUtils.isNotEmpty(height) && width > 0 && height > 0) {
                double ratio = width.doubleValue() / height.doubleValue();
                BigDecimal bd = new BigDecimal(ratio).setScale(2, RoundingMode.HALF_UP); // 四舍五入
                return bd.doubleValue(); // 返回 double，如 1.33
            }
        }
        return 0.0;
    }

    private static String getFileName(MultipartFile file) throws IOException {
        // 1. 获取文件的真实 MIME 类型
        String contentType = file.getContentType();
        if (contentType == null) {
            throw new IllegalArgumentException("无法识别文件类型");
        }

        // 2. 判断是图片还是文档
        String fileType = getFileType(contentType);

        if ("unknown".equals(fileType)) {
            throw new IllegalArgumentException("不支持的文件类型: " + contentType);
        }

        // 3. 获取正确的扩展名
        String extension = "image".equals(fileType)
                ? ALLOWED_IMAGE_TYPES.get(contentType)
                : ALLOWED_DOCUMENT_TYPES.get(contentType);

        // 4. 生成唯一文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");
        if ("image".equals(fileType)) {
            Map<String, Integer> imageDimensions = getImageDimensions(file);
            Integer width = imageDimensions.get("width");
            Integer height = imageDimensions.get("height");
            fileName += "_" + height + "×" + width;
        }

        fileName = fileName + "." + extension;// uuid_500×50.jpg

        // 5. 按日期分类存储路径
        LocalDate currentDate = LocalDate.now();
        String datePath = currentDate.format(DateTimeFormatter.ofPattern("yyMM/dd"));
        String storagePath = fileType + "/" + datePath + "/" + fileName; // e.g., "images/2503/15/xxx_500×50.jpg"

        return storagePath;
    }


    /**
     * 获取文件的类型
     *
     * @param contentType
     * @return
     */
    private static String getFileType(String contentType) {
        if (ALLOWED_IMAGE_TYPES.containsKey(contentType)) {
            return "image";
        } else if (ALLOWED_DOCUMENT_TYPES.containsKey(contentType)) {
            return "file";
        } else {
            return "unknown";
        }
    }


    /**
     * 获取图片的长度和宽度
     *
     * @param file
     * @return
     * @throws IOException
     */
    private static Map<String, Integer> getImageDimensions(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream()) {
            BufferedImage image = ImageIO.read(inputStream);
            if (image == null) {
                throw new IllegalArgumentException("上传的文件不是有效的图片");
            }
            int width = image.getWidth();
            int height = image.getHeight();
            return Map.of("width", width, "height", height);
        }
    }

}
